<!-- filepath: d:\code\code_xiezuowang\xiezuowang\code\personCenterWeb\src\views\information\imagesUpload\pullform.vue -->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="50%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span>{{ getTitle.value }}</span>
    </template>
    <div>
      <Icon icon="ant-design:question-circle-outlined" class="ml-2" style="margin-left: 40px" />
      <span style="margin-left: 8px">您将授权我们获取以下平台的数据</span>
      <BasicForm @register="registerForm" @change="onFormChange" />
    </div>
  </BasicDrawer>
  <!-- <a-modal
    v-model:open="confirmVisible"
    title="确认拉取"
    @ok="handleConfirm"
    @cancel="confirmVisible = false"
    ok-text="确认"
    cancel-text="取消"
  >
    <p>确定要拉取所选平台的数据吗？</p>
  </a-modal> -->
</template>

<script lang="ts" setup name="ViewsInformationPullForm">
  import { ref, computed, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import axios from 'axios';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('information.imagesUpload');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    value: t('拉取平台数据'),
  }));

  const confirmVisible = ref(false);
  const selectedPlatforms = ref<string[]>([]);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('医院名称'),
      field: 'platforms',
      component: 'Select',
      componentProps: {
        options: [
          { label: '众阳', value: 'zhongyang' },
          { label: '颐乐居', value: 'yileju' },
          { label: '中山', value: 'zhongshan' },
          { label: '哈尔滨市呼兰区第一人民医院', value: 'hulan' },
        ],
        // mode: 'multiple',
        maxlength: 1000,
        onChange: (val: string[] | string) => {
          const arr = Array.isArray(val) ? val : [val];
          if (arr.length > 0 && JSON.stringify(arr) !== JSON.stringify(lastPlatforms.value)) {
            confirmVisible.value = true;
            lastPlatforms.value = [...arr];
            handleConfirm();
          }
        },
      },
      required: true,
    },
    {
      label: t('结果'),
      field: 'description',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 1000,
        autoSize: true,
      },
    },
  ];

  const [registerForm, { setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 48 },
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner();

  const lastPlatforms = ref<string[]>([]);

  function onFormChange({ values }) {
    // 只有平台变化且和上次不同才弹出确认框
    if (
      values.platforms &&
      values.platforms.length > 0 &&
      JSON.stringify(values.platforms) !== JSON.stringify(lastPlatforms.value)
    ) {
      confirmVisible.value = true;
      lastPlatforms.value = [...values.platforms];
      console.log('Selected platforms:', values.platforms);
      handleConfirm();
    }
  }

  const pulledData = ref();
  async function handleConfirm() {
    confirmVisible.value = false;
    setDrawerProps({ confirmLoading: true });
    try {
      // 拉取数据
      console.log('拉取平台数据:', lastPlatforms.value);
      const res = await pullPlatformData(lastPlatforms.value);
      const report = res.data.report || '';
      const dataArr = res.data.data || [];
      pulledData.value = dataArr;
      // 拼接 data
      const dataStr = Array.isArray(dataArr)
        ? dataArr
            .map(
              (item) =>
                `- 机构：${item.agency_name}\n  服务类别：${item.service_category}\n  项目类型：${item.project_type}\n  服务内容：${item.service_content}\n  时间：${item.appointment_time}\n`,
            )
            .join('\n\n')
        : '';
      // 拼接最终 description
      // const desc = `${report}\n${dataStr}`;
      //模拟平台返回数据
      const desc =
        '主诉：咳嗽多日。检查：血常规：无异常； 肺炎支原体抗体：阴性。药物：拜阿斯匹林：口服，一次 100mg, 晚饭后; 匹伐他汀: 睡前一片; 依折麦布: 一片/次 一日一次; 易善复: 两粒/次一日三次 。诊断：肺炎。建议：。复诊：1周后复查血细胞分析, 一月后复查肝功能、血脂。';
      // 回填到表单
      setFieldsValue({
        platforms: Array.isArray(lastPlatforms.value) ? lastPlatforms.value : [lastPlatforms.value],
        description: desc,
      });
      showMessage('拉取成功');
      console.log('拉取结果:', pulledData.value);
    } catch (e) {
      console.error('拉取失败:', e);
      showMessage('拉取失败');
    } finally {
      const desc =
        '主诉：咳嗽多日。检查：血常规：无异常； 肺炎支原体抗体：阴性。药物：拜阿斯匹林：口服，一次 100mg, 晚饭后; 匹伐他汀: 睡前一片; 依折麦布: 一片/次 一日一次; 易善复: 两粒/次一日三次 。诊断：肺炎。建议：。复诊：1周后复查血细胞分析, 一月后复查肝功能、血脂。';
      setFieldsValue({
        platforms: Array.isArray(lastPlatforms.value) ? lastPlatforms.value : [lastPlatforms.value],
        description: desc,
      });
      setDrawerProps({ confirmLoading: false });
    }
  }

  // 拉取平台数据的异步函数（实际可替换为后端API）
  // async function pullPlatformData(platforms: string[]) {
  //   await new Promise((r) => setTimeout(r, 1200));
  //   return [
  //     { id: '1', time: '2025-06-04 10:00', type: '众阳', description: '众阳平台数据' },
  //     { id: '2', time: '2025-06-04 11:00', type: '颐乐居', description: '颐乐居平台数据' },
  //     { id: '3', time: '2025-06-04 12:00', type: '中山', description: '中山平台数据' },
  //   ];
  //   // .filter((item) =>
  //   //   platforms.includes(
  //   //     item.type === '众阳' ? 'zhongyang' : item.type === '颐乐居' ? 'yileju' : 'zhongshan',
  //   //   ),
  //   // );
  // }
  async function pullPlatformData(platforms: string[]) {
    // await new Promise((r) => setTimeout(r, 200));
    // return [
    //   { id: '1', time: '2025-06-04 10:00', type: '众阳', description: '众阳平台数据' },
    //   { id: '2', time: '2025-06-04 11:00', type: '颐乐居', description: '颐乐居平台数据' },
    //   { id: '3', time: '2025-06-04 12:00', type: '中山', description: '中山平台数据' },
    // ];
    // const response = await axios.post(
    //   'http://localhost:8010/pull-data',
    //   { id: '110223********0576' },
    //   {
    //     timeout: 60000,
    //     headers: {
    //       'Content-Type': 'application/json',
    //     },
    //   },
    // );
    const id_1 = '110223********0576';
    const response = await axios.post(
      `http://localhost:8010/pull-data`,
      { id: id_1 },
      {
        timeout: 60000,
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
    console.log('API 响应:', response.data);
    return response;
  }

  async function handleSubmit() {
    console.log('registerDrawer in pullform:', registerDrawer);
    try {
      setDrawerProps({ confirmLoading: true });
      // if (!platforms.length) {
      //   showMessage('请至少选择一个平台');
      //   setDrawerProps({ confirmLoading: false });
      //   return;
      // }
      emit('success', pulledData);
      showMessage('拉取成功');
      setTimeout(closeDrawer, 300);
    } catch (error) {
      showMessage('拉取失败');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
